/*
Assignment 1
Class ID        : SE0691
Group           : 1
Due Date        : 20 November 2012
I declare that this assignment is my own work
in accordance with FPT Policy.
*/
package edu.fpt.dal;

import edu.fpt.hib.HibernateUtil;
import edu.fpt.hib.News;
import java.util.ArrayList;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Admin
 */
public class NewsDAL {
    public static ArrayList<News> listAll() {
        Session session = null;
        Transaction tran = null;
        try {
            session = (Session) HibernateUtil.getSessionFactory().openSession();
            tran = session.beginTransaction();
            ArrayList<News> list = new ArrayList<News>();
            Query query = session.createQuery("from News ORDER BY newsDate DESC");
            list = (ArrayList<News>) query.list();
            tran.commit();
            return list;
        } finally {
            session.close();
        }
    }
    public static void insert(News entity) {
        Session session = null;
        Transaction tran = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            tran = session.beginTransaction();
            session.save(entity);
            tran.commit();
        } finally {
            session.close();
        }
    }
    
    public static void update(News entity) {
        Session session = null;
        Transaction tran = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            tran = session.beginTransaction();
            session.update(entity);
            tran.commit();
        } finally {
            session.close();
        }
    }
    
    public static void delete(News entity) {
        Session session = null;
        Transaction tran = null;
        try {
            session = (Session) HibernateUtil.getSessionFactory().openSession();
            tran = session.beginTransaction();
            session.delete(entity);
            tran.commit();
        } finally {
            session.close();
        }
    }
    
    public static News getNews(int newsID) {
        Session session = null;
        Transaction tran = null;
        try {
            session = (Session) HibernateUtil.getSessionFactory().openSession();
            tran = session.beginTransaction();
            Query query = session.createQuery("from News where newsId = :newsid");
            query.setParameter("newsid", newsID);
            News news = (News) query.uniqueResult();
            tran.commit();
            return news;
        } finally {
            session.close();
        }
    }
}
